#include <iostream>
#include <pthread.h>
#include <vector>
#include <ctime>
using namespace std;

int count = 0;
pthread_spinlock_t spin_lock;
pthread_mutex_t mutex;

#define TIMES 10000000
void* addUp(void*) {
    // pthread_spin_lock(&spin_lock);
    pthread_mutex_lock(&mutex);

    for (int i = 0; i < TIMES; ++i) {
        ++count;
    }

    pthread_mutex_unlock(&mutex);
    // pthread_spin_unlock(&spin_lock);
}
#undef TIMES


//* 测出来居然是mutex更快
int main() {
    pthread_spin_init(&spin_lock, 0);
    pthread_mutex_init(&mutex, nullptr);

    clock_t begin = clock();
    vector<pthread_t> threads(10);
    for (auto& thread : threads) {
        pthread_create(&thread, nullptr, addUp, nullptr);
    }

    for (auto& thread : threads) {
        pthread_join(thread, nullptr);
    }
    clock_t end = clock();

    cout << "消耗时间：" << (end - begin) << " ticks, 1s = 1000 0000 ticks"<< endl;
    cout << "结果为：" <<count << endl;
    pthread_spin_destroy(&spin_lock);
    pthread_mutex_destroy(&mutex);
    return 0;
}